<template>
	<div>
		<div class="flex flex-row items-center mb-3">
			<CalendarToolbar
				ref="calendarToolbar"
				@changeView="onViewChange"
				@changeDate="onDateChange"
				:queryList="queryList"
			/>
		</div>
		<FullCalendar class="demo-app-calendar" ref="fullCalendarRef" :options="calendarOptions">
			<template #eventContent="arg">
				<a-popover trigger="click" v-if="gridType !== 'dayGridMonth'" :title="arg.event.title">
					<template #content>
						<div class="flex flex-row justify-end">
							<a-space wrap>
								<a-button type="primary" @click="edit(arg.event.extendedProps)">修改</a-button>
								<a-button type="primary" @click="detail(arg.event.extendedProps)">查看详情</a-button>
							</a-space>
						</div>
						<!-- <div class="flex flex-col justify-center w-full p-1 box-border">
							<div class="flex flex-col justify-between">
								<div class="flex">
									<span>{{ arg.event.extendedProps.type === 'schedule' ? '日程' : '会议' }}</span>
								</div>
								<div class="absolute top-0 right-0 m-1 cursor-pointer">
									<a-popconfirm
										title="确定移除吗？"
										ok-text="确定"
										cancel-text="取消"
										@confirm.stop="back(arg.event)"
										@cancel="cancel"
									>
										<CloseOutlined @click.stop />
									</a-popconfirm>
								</div>
							</div>
							<div class="flex flex-row items-center justify-between">
								<div class="flex flex-row items-center">
									<n-icon :size="14">
										<PersonCircleSharp />
									</n-icon>
									<div class="ml-[4px]">
										<div class="no_wrap">
											{{
												arg.event.extendedProps.RESERVATION_TITLE
													? arg.event.extendedProps.calendarType
													: arg.event.extendedProps.calendarType
											}}
										</div>
									</div>
								</div>
							</div>
							<div class="flex flex-row items-center">
								<n-icon :size="14">
									<AlarmSharp />
								</n-icon>
								<div class="ml-[4px] w-[90%]">
									<div class="no_wrap">
										{{ arg.timeText ? arg.timeText : '全天' }}
									</div>
								</div>
							</div>
							<div class="flex flex-row items-center">
								<n-icon :size="14">
									<ReaderSharp />
								</n-icon>
								<div class="ml-[4px] w-[90%]">
									<div class="no_wrap">
										{{ arg.event.extendedProps.RESERVATION_DEPT }}
									</div>
								</div>
							</div>
						</div> -->
					</template>
					<!-- <template #footer>
						<div class="flex flex-row justify-end">
							<a-space wrap>
								<a-button type="primary" @click="edit(arg.event.extendedProps)">修改</a-button>
								<a-button type="primary" @click="detail(arg.event.extendedProps)">查看详情</a-button>
							</a-space>
						</div>
					</template> -->
					<template #default>
						<div class="w-[300px]">
							<div class="border-t-4 border-indigo-500 w-full divide-y divide-slate-200"></div>
							<b>{{ arg.timeText }}</b
							><i>{{ arg.event.title }}</i>
							<div class="absolute top-0 right-0 m-1 cursor-pointer">
								<a-popconfirm
									title="确定移除吗？"
									ok-text="确定"
									cancel-text="取消"
									@confirm.stop="back(arg.event)"
									@cancel="cancel"
								>
									<CloseOutlined @click.stop />
								</a-popconfirm>
							</div>
						</div>
					</template>
				</a-popover>
				<template v-else>
					<div class="flex items-center flex-wrap w-full p-1 box-border">
						<div class="ml-[4px] bg-[#3975c6] text-white px-2 rounded">
							{{ arg.event.extendedProps.type === 'schedule' ? '日程' : '会议' }}
						</div>
						<div class="ml-[4px]">
							{{
								arg.event.extendedProps.leaderNames.length === 1
									? arg.event.extendedProps.leaderNames[0]
									: `${arg.event.extendedProps.leaderNames[0]}等`
							}}
						</div>
						<div class="ml-[4px] font-bold">
							{{ arg.event.extendedProps.title }}
						</div>
						<div class="ml-[4px]">
							{{ arg.timeText ? arg.timeText : '全天' }}
						</div>
					</div>
				</template>
			</template>
		</FullCalendar>
		<Form ref="formRef" @successful="queryList()" />
	</div>
</template>
<script setup lang="ts">
	import FullCalendar from '@fullcalendar/vue3'
	import dayGridPlugin from '@fullcalendar/daygrid'
	import interactionPlugin from '@fullcalendar/interaction'
	import timeGridPlugin from '@fullcalendar/timegrid'
	import zhCN from '@fullcalendar/core/locales/zh-cn'
	import { ScheduleEntity } from '@/views/biz/calendarmanagement/types'
	import CalendarToolbar from '@/views/biz/calendarmanagement/components/calendarToolbar.vue'
	import Form from '@/views/biz/calendarmanagement/form.vue'
	import moment from 'moment'
	import calendar from '@/views/biz/calendarmanagement/lunarDay.js'
	import Lunar from 'lunar-javascript'
	import bizCalendarManagementApi from '@/api/biz/bizCalendarManagementApi'
	const fullCalendarRef = ref(null)
	const calendarToolbar = ref(null)
	const formRef = ref(null)
	const todoListRef = ref(null)
	const scheduleModalRef = ref(null)
	const currentEvents = ref([]) //预约列表
	const gridType = ref('') //周日月切换类型
	onMounted(() => {
		calendarToolbar.value.refreshTitle(`${fullCalendarRef.value.getApi().view.title}`)
		queryList()
	})
	const onViewChange = (view) => {
		gridType.value = view
		fullCalendarRef.value.getApi().changeView(view)
		calendarToolbar.value.refreshTitle(`${fullCalendarRef.value.getApi().view.title}`)
	}
	const onDateChange = (opt) => {
		let api = fullCalendarRef.value.getApi()
		if (opt === 'prev') {
			api.prev()
		} else if (opt === 'next') {
			api.next()
		} else if (opt === 'today') {
			api.today()
		}
		calendarToolbar.value.refreshTitle(fullCalendarRef.value.getApi().view.title)
	}
	const handleEventClick = (info) => {
		console.log(info, 'info')
	}
	const handleEventAdd = (info) => {
		console.log(info)
	}
	//点击日期
	const dateClick = (event) => {
		console.dir(event, 'e')
		formRef.value.onOpen()
		// formRef.value.formData = event.id
	}
	const comAction = {
		// 是否节假日
		isFestival(slotData) {
			const formattedDate = moment(slotData).format('YYYY-MM-DD')
			let solarDayArr = formattedDate.split('-')
			let lunarDay = calendar.solar2lunar(solarDayArr[0], solarDayArr[1], solarDayArr[2])

			// 公历节日\农历节日\农历节气
			let festAndTerm = []
			festAndTerm.push(lunarDay.festival == null ? '' : ' ' + lunarDay.festival)
			festAndTerm.push(lunarDay.lunarFestival == null ? '' : '' + lunarDay.lunarFestival)
			festAndTerm.push(lunarDay.Term == null ? '' : '' + lunarDay.Term)
			festAndTerm = festAndTerm.join('')

			return festAndTerm
		}
	}
	// const eventBgColor = ref('#5ed536')
	const eventBgColor = ref('#ccc')
	const calendarOptions = ref({
		plugins: [
			dayGridPlugin,
			timeGridPlugin,
			interactionPlugin // needed for dateClick
		],
		titleRangeSeparator: '至',
		footerToolbar: false,
		headerToolbar: false,
		locale: zhCN,
		aspectRatio: 2,
		events: currentEvents,
		eventBorderColor: 'transparent',
		eventBackgroundColor: eventBgColor,
		slotMinTime: '08:00', // 日历开始时间设为8点
		slotMaxTime: '24:00', // 日历结束时间设为12点
		initialView: 'timeGridWeek',
		droppable: true,
		selectable: false,
		selectMirror: true,
		dayMaxEvents: true,
		weekends: true,
		moreLinkText: '查看全部',
		allDaySlot: false,
		slotLabelClassNames: 'slotLabel',
		eventAdd: handleEventAdd,
		eventClick: handleEventClick,
		dateClick: dateClick,
		dayCellContent: (arg) => {
			const solar = Lunar.Solar.fromDate(arg.date)
			const lunar = solar.getLunar()
			if (gridType.value === 'dayGridMonth') {
				return {
					html: `
	       <div class="fc-daygrid-day-top">
	  		<div class="fc-daygrid-day-number">
	   			<div style="float: right; text-align: right;">${arg.dayNumberText}</div>
		  	</div>
	       </div>
	       <div style="float: right; text-align: right;">${comAction.isFestival(arg.date)}</div>
	       <div style="text-align: right">${lunar.getDayInChinese()}</div>
	     `
				}
			} else {
				return
			}
		}
	})
	/**
	 * 查询列表
	 */
	const queryList = () => {
		bizCalendarManagementApi.bizCalendarManagementPage().then((res) => {
			console.log(res)

			// console.log(res);
			if (res.records) {
				let tmp = []
				res.records.forEach((item: ScheduleEntity) => {
					tmp.push({
						id: item.id,
						title: item.calendarType,
						start: `${item.startDate}`,
						end: `${item.endDate}`,
						extendedProps: {
							...item,
							confirm: true
						}
						// backgroundColor: item.ISEND === '0' ? '#0097fa' : '#ff6200' //背景颜色
					})
				})
				currentEvents.value = tmp
			} else {
				currentEvents.value = []
			}
		})
	}

	const edit = (t) => {
		console.log(t, 888)
		formRef.value.onOpen()
		formRef.value.setData(t)
		// scheduleModalRef.value.showModal(t, false)
	}
	const detail = (t) => {
		formRef.value.onOpen(t)
		// scheduleDetailRef.value.activate(t);
	}
	const back = (event) => {
		console.log(event._def.extendedProps.id)
		bizCalendarManagementApi.bizCalendarManagementDelete([{ id: event._def.extendedProps.id }]).then((res) => {
			queryList()
		})
		// queryScheduleDetail({ id: event.extendedProps.id }).then((res) => {
		//   const eventData = res.data;
		//   eventData.scheduleStatus = 0;
		//   eventData.startTime = null;
		//   eventData.endTime = null;
		//   eventData.ifAllDay = !event.end;
		//   scheduleAdd(eventData).then((response) => {
		//     if (response.code === 200) {
		//       message.success("移除成功");
		//       todoListRef.value.queryTodoList();
		//       event.setExtendedProp("confirm", true);
		//       event.remove();
		//     } else {
		//       message.error(response.msg);
		//     }
		//   });
		// });
	}
	const cancel = (e: MouseEvent) => {
		console.log(e)
	}
</script>
<style scoped lang="less">
	:deep(.main-content-wrapper) {
		background-color: #fff;
	}
	:deep(.fc-col-header) {
		height: 50px !important;
		line-height: 50px;
		font-size: larger;
		width: 100% !important;
	}
</style>
